import { sha1 } from '~/utils';
import { XMLParser } from 'fast-xml-parser';
import replyCallback from '~/utils/reply';
import { textMessage } from '~/utils/template';

const xmlParser = new XMLParser();

export default defineEventHandler(async (event) => {
  if (event.method === 'GET') {
    const query = getQuery(event);
    const signature = query.signature;
    const echostr = query.echostr;
    const timestamp = query.timestamp;
    const nonce = query.nonce;
    let oriArray = [nonce, timestamp, event.context.cloudflare.env.APP_TOKEN];
    oriArray.sort();
    const original = oriArray.join('');
    let scyptoString = await sha1(original);
    if (signature == scyptoString) {
      return echostr || 'error';
    } else {
      return 'error';
    }
  }
  if (event.method === 'POST') {
    const body = await readBody(event);
    const msg = xmlParser.parse(body).xml;
    console.log('msg:', msg);
    const Content = msg.Content;
    let reply = await replyCallback(Content, event.context.cloudflare.env);
    switch (msg.MsgType) {
      case 'text':
        // 封装要回复的消息参数
        let message = {
          FromUserName: msg.FromUserName,
          ToUserName: msg.ToUserName,
          reply: reply,
        };
        return textMessage(message);

      default:
        return ''; // 不是文本消息是默认响应一个空
    }
  }
  return 'ok';
})
